from Bases import Config
from comm.CommDispatcher import CommDispatcherBase

class CommDispatcher(CommDispatcherBase, Config):
    _confsection = 'Comm'
    def __init__(self, **kwargs):
        CommDispatcherBase.__init__(self, **kwargs)
        Config.__init__(self, **kwargs)
        keys = [key for key in self.IO_CLASSES.keys() if 'dmx' in key]
        self.io_classes = dict(zip([key.split('.')[1] for key in keys], [self.IO_CLASSES[key] for key in keys]))
        self._MainController = None
        self.register_signal('io_update', 'MainController_set')
        self.dmx_io = {}
        self.osc_io = self.build_io_module('osc', updn_order=True)
        io_keys = self.get_conf('dmx_io', [])
        for key in io_keys:
            self.build_io(key, update_conf=False)
        self._hostaddr = self.get_conf('host_address')
        self._hostiface = self.get_conf('host_interface')
        self.midi_io = self.build_io_module('midi', updn_order=True)
    @property
    def hostaddr(self):
        if self._hostaddr:
            return self._hostaddr
        return self.detect_usable_address()
    @property
    def MainController(self):
        return self._MainController
    @MainController.setter
    def MainController(self, value):
        self._MainController = value
        self.emit('MainController_set')
    def build_io(self, name, **kwargs):
        update_conf = kwargs.get('update_conf', True)
        modname = '.'.join(['dmx', name])
        obj = self.build_io_module(modname, updn_order=True, **kwargs)
        self.dmx_io[name] = obj
        self.emit('io_update', key=name)
        if update_conf:
            self.update_conf(dmx_io=self.dmx_io.keys())
        if self.connected:
            obj.do_connect()
    def remove_io(self, name, **kwargs):
        update_conf = kwargs.get('update_conf', True)
        modname = '.'.join(['dmx', name])
        obj = self.remove_io_module(modname)
        if obj is None:
            return
        del self.dmx_io[name]
        if update_conf:
            self.update_conf(dmx_io=self.dmx_io.keys())
        self.emit('io_update', key=name)
